package org.m2acsi.control;

import java.io.Serializable;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.annotation.ManagedBean;
import javax.enterprise.context.RequestScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import org.m2acsi.boundary.ConsultationEJB;
import org.m2acsi.boundary.DocumentEJB;
import org.m2acsi.entities.Document;
import org.m2acsi.entities.Download;
import org.m2acsi.entities.Task;
import org.m2acsi.utils.Security;

@Named
@RequestScoped
@ManagedBean
public class DocumentBean extends BaseBean implements Serializable {

    @Inject
    private DocumentEJB documentEJB;
    @Inject
    private ConsultationEJB consultationEJB;

    public DocumentBean() {
        super();
    }

    public List<Document> getDocuments() {
        Task tmpTask = Security.taskSecurityCheck(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("id"), getAuthenticatedUser(), taskEjb, this);
        Date lastVisit = consultationEJB.lastConsultationOnTaskDetails(tmpTask, getAuthenticatedUser());
        List<Document> documents = documentEJB.findAll(tmpTask);
        for (Iterator<Document> it = documents.iterator(); it.hasNext();) {
            Document d = it.next();

            d.setIsNew(true);
            for (Iterator<Download> it1 = d.getDownloads().iterator(); it1.hasNext();) {
                Download dl = it1.next();
                if (dl.getUser().getId() == getAuthenticatedUser().getId()) {
                    d.setIsNew(false);
                    break;
                }
            }
        }
        return documents;
    }
}
